import React, { useState, useEffect } from 'react'
import { Col, Form, Input, Button, Tabs, Row, Select, Table, Avatar, Modal, DatePicker } from 'antd'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import RenderButtom from '@/components/RenderButton'
import SearchBox from '@/components/SearchBox'
import { router } from 'umi'
import { getSupplierList, getProductList, getStoreList, batchPutaway, batchSoldout, shiftDelete } from '@/services/goodCenter/goodsManage/goodsRecycle'
import storeList from '@/pages/supplier/store/storeList'

const { TextArea } = Input

const { Option } = Select

const { RangePicker } = DatePicker

// 表头
const columns = [
  {
    title: '商品名称',
    dataIndex: 'goodsName',
    key: 'goodsName',
    align: 'center'
  },
  {
    title: '店铺名称',
    dataIndex: 'storeName',
    key: 'storeName',
    align: 'center'
  },
  {
    title: '价格',
    dataIndex: 'shopPrice',
    key: 'shopPrice',
    align: 'center'
  },
  {
    title: '总库存',
    dataIndex: 'goodsStockNum',
    key: 'goodsStockNum',
    align: 'center'
  },
  {
    title: '总销量',
    dataIndex: 'goodsWhsNum',
    key: 'goodsWhsNum',
    align: 'center'
  },
  {
    title: '商品编码',
    dataIndex: 'goodsCode',
    key: 'goodsCode',
    align: 'center'
  },
  {
    title: '排序',
    dataIndex: 'goodsSort',
    key: 'goodsSort',
    align: 'center'
  },
  {
    title: '创建时间',
    dataIndex: 'createDate',
    key: 'createDate',
    align: 'center'
  }
]

const GoodsRecycle = props => {
  const { form } = props
  const { getFieldDecorator } = form
  const [total, setTotal] = useState(1)
  const [pageNo, setPageNo] = useState(1)
  const [pageSize, setPageSize] = useState(10)
  const [record, setRecord] = useState({})
  const [sizeList, setSizeList] = useState([])
  const [catList, setCatList] = useState([])
  const [visible, setVisible] = useState(false)
  const [productList, setProductList] = useState([])
  const [supplierList, setSupplierList] = useState([])
  const [storeList, setStoreList] = useState([])
  const [startTime, setStartTime] = useState('')
  const [endTime, setEndTime] = useState('')
  const [isAdmin, setIsAdmin] = useState(1)
  const [listStatus, setListStatus] = useState([0])
  const [page, setPage] = useState({
    isAsc: '',
    orderByField: ''
  })

  const rowSelection = {
    type: 'radio',
    onChange: (selectedRowKeys, selectedRows) => {
      setRecord(selectedRows)
      // console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
      console.log(record)
    },
  }

  useEffect(() => {
    init()
  }, [])
  const init = async () => {
    await getSupplierLists()
    let params = {
      isAdmin,
      listStatus,
      page,
      pageNo,
      pageSize
    }
    await getProductLists(params)
  }
  // 表单查询
  const handleSearch = e => {
    e.preventDefault()
    form.validateFields(async (err, values) => {
      console.log('Received values of form: ', values)
      let params = {
        isAdmin,
        listStatus,
        page,
        pageNo,
        pageSize,
        goodsCode: values.goodsCode,
        goodsName: values.goodsName,
        storeId: values.storeId,
        supplierId: values.supplierId,
        startTime,
        endTime
      }
      await getProductLists(params)
    })
  }
  // 表单清空
  const handleReset = e => {
    form.resetFields();
  }
  // 查询条件
  const getFields = () => {
    return(
      <Row gutter={24}>
        <Col span={8}>
          <Form.Item label="商品名称" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('goodsName', {})
              (<Input placeholder="请输入商品名称" />)}
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item label="所属商户" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('supplierId', {})
              (<Select
                style={{ width: '100%' }}
                showSearch
                filterOption={(input, option) => option.props.children.indexOf(input) >= 0}
                placeholder="请选择"
                onChange={selectSupplier}
              >
                { supplierList && supplierList.map(r => <Option key={r.id} value={r.id}>{r.merchantName}</Option>)}
              </Select>)}
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item label="门店" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('storeId', {})
              (<Select
                style={{ width: '100%' }}
                showSearch
                filterOption={(input, option) => option.props.children.indexOf(input) >= 0}
                placeholder="请选择"
              >
                { storeList && storeList.map(r => <Option key={r.id} value={r.id}>{r.name}</Option>)}
              </Select>)}
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item label="商品编码" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('goodsCode', {})
              (<Input placeholder="请输入商品编码" />)}
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item label="创建时间" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('data', {})
              (<RangePicker onChange={onChange} />)}
          </Form.Item>
        </Col>
      </Row>
    )
  }
  // 按钮处理
  const handleBtn = async type => {
    console.log(type)
    if (JSON.stringify(record) === '{}') return
    switch (type) {
      // 还原到出售当中
      case 3:
        await batchPutaways(record[0].id)
        break
      // 还原到仓库当中
      case 12:
        await batchSoldouts(record[0].id)
        break
      case 4:
      // 测试删除
        await shiftDeletes(record[0].id)
        break
    }
  }

  const pagination = {
    total: parseInt(total),
    onChange(page) {

    }
  }

  // 获取商户列表
  const getSupplierLists = async () => {
    let res = await getSupplierList()
    if (res.code === '0') {
      setSupplierList(res.data)
    } else {
      alert(res.msg)
    }
  }
  // 获取商品列表
  const getProductLists = async (params) => {
    let res = await getProductList(params)
    if (res.code === '0') {
      setProductList(res.data)
      setTotal(res.iTotalDisplayRecords)
    } else {
      alert(res.msg)
    }
  }
  // 获取商品列表
  const getStoreLists = async (params) => {
    let res = await getStoreList(params)
    if (res.code === '0') {
      setStoreList(res.data)
    } else {
      alert(res.msg)
    }
  }
  // 选择商户
  const selectSupplier = async (supplierId) => {
    let params = {
      pageSize: 999,
      supplierId
    }
    await getStoreLists(params)
  }
  // 还原到出售中
  const batchPutaways = async (id) => {
    let params = {
      listId: [id]
    }
    let res = await batchPutaway(params)
    if (res.code === '0') {
      alert(res.msg)
      init()
    } else {
      alert(res.msg)
    }
  }
  // 还原到仓库中
  const batchSoldouts = async (id) => {
    let params = {
      listId: [id]
    }
    let res = await batchSoldout(params)
    if (res.code === '0') {
      alert(res.msg)
      init()
    } else {
      alert(res.msg)
    }
  }
  // 彻底删除
  const shiftDeletes = async (id) => {
    let params = {
      listId: [id]
    }
    let res = await shiftDelete(params)
    if (res.code === '0') {
      alert(res.msg)
      init()
    } else {
      alert(res.msg)
    }
  }

  const onChange = (date, dateString) => {
    console.log(date, dateString)
    setStartTime(dateString[0])
    setEndTime(dateString[1])
  }

  return (
    <PageHeaderWrapper>
      <SearchBox handleReset={handleReset} handleSearch={handleSearch} getFields={getFields} />
      <RenderButtom click={handleBtn} />
      <Table
        columns={columns}
        dataSource={productList}
        rowKey={record => record.id}
        pagination={pagination}
        rowSelection={rowSelection}
      />
   </PageHeaderWrapper>
  )
}

export default Form.create()(GoodsRecycle)
